package com.example.roadeyeserver.config;

import com.example.roadeyeserver.datasource.DynamicDataSourceContextHolder;
import com.example.roadeyeserver.datasource.DynamicDatasource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties
@Slf4j
public class DataSourceConfig {
    // 获取前缀为`db1.datasource`的配置项
    @Bean
    @ConfigurationProperties(prefix = "db1.datasource")
    public HikariConfig db1Config() {
        return new HikariConfig();
    }

    // 获取前缀为`db2.datasource`的配置项
    @Bean
    @ConfigurationProperties(prefix = "db2.datasource")
    public HikariConfig db2Config() {
        return new HikariConfig();
    }


    @Bean
    public DataSource getDatasource(@Value("${datasource.db2.enabled:true}") boolean db2Enabled) {
        // 将数据源存入map集合
        Map<Object, Object> dataSourceMap = new HashMap<>();
        DataSource db1 = new HikariDataSource(db1Config());
        dataSourceMap.put("db1", db1);

        // 只有当db2启用时才尝试创建
        if (db2Enabled) {
            try {
                DataSource db2 = new HikariDataSource(db2Config());
                dataSourceMap.put("db2", db2);
                // 记录多数据源名称
                DynamicDataSourceContextHolder.dataSources.add("db2");
            } catch (Exception e) {
                log.error("db2数据源初始化失败，将跳过该数据源", e);
            }
        }

        // 设置动态数据源
        DynamicDatasource dataSource = new DynamicDatasource();
        dataSource.setTargetDataSources(dataSourceMap);

        // 记录多数据源名称
        DynamicDataSourceContextHolder.dataSources.add("db1");
        DynamicDataSourceContextHolder.dataSources.add("db2");

        // 设置默认的数据源
        dataSource.setDefaultTargetDataSource(db1);
        return dataSource;
    }
}
